<?php
/**
 * Nuclide Controller dispatcher
 * 
 * @package	Nuclide-Mvc
 * @version $Id$
 */

Zend_Loader::loadClass('Zend_Controller_Dispatcher_Standard');
Zend_Loader::loadClass('Zend_Controller_Dispatcher_Exception');

/**
 * Enhanced Controller dispatcher
 * 
 * @package	Nuclide-Mvc
 */
class nuc_Controller_Dispatcher extends Zend_Controller_Dispatcher_Standard
{
	/**
	 * Class loader
	 * 
	 * @var nuc_Loader|bool
	 */
	protected $_classLoader = false;
	
	/**
	 * Public constructor
	 * 
	 * @param	array		Dispatcher parameters
	 * @param	nuc_Loader	Class loader
	 */
	public function __construct( array $params = array(), nuc_Loader $classLoader ) {
		parent::__construct( $params );
		
		$this->_classLoader = $classLoader;
	}
	
	/**
	 * Find out if a request is dispatchable.
	 *
	 * @param	Zend_Controller_Request_Abstract	Request
	 * @return	true = success, false = failure
	 */
	public function isDispatchable( Zend_Controller_Request_Abstract $request ) {
		$className = $this->getControllerClass( $request );
        if( $className == false ) {
            return true;
        }

        if( class_exists( $className ) && is_subclass_of( $className, 'Zend_Controller_Action' ) ) {
    		return true;
        } else if( $this->_classLoader->classLoadable( $className ) ) {
        	return true;
        } else {
        	return false;
        }
	}

	/**
	 * Simulate desired behaviour for Zend_Controlloer_Dispatcher_Standard.
	 *
	 * @param	string		Class name
	 * @return	Class name
	 */
	public function loadClass( $className ) {
		if( class_exists( $className ) == false ) {
			$this->_classLoader->loadClass( $className );
		}
		
		return $className;
	}
	
	/**
	 * Gets the dispatcher class loader
	 * 
	 * @return	Class loader 
	 */
	public function getClassLoader() {
		return $this->_classLoader;
	}

	/**
	 * Returns a class filename using the class
	 * 
	 * @return	Class filename
	 */
	public function classToFilename( $class ) {
    	return $this->_classLoader->classToFilename( $class );
    }
	
	/**
	 * Format a string into a controller class name.
	 *
	 * @param	string	Unformatted controller name
	 * @return	string
	 */
	public function formatControllerName( $unformatted ) {
		return $unformatted;
	}
	
	/**
	 * Format a string into an action method name.
	 *
	 * @param	string	Unformatted action method name
	 * @return	string
	 */
	public function formatActionName( $unformatted ) {
		return $unformatted;
	}
}
?>